package com.simon.system.service.impl;

import com.github.pagehelper.PageHelper;
import com.simon.exception.OperationFailedException;
import com.simon.http.model.PResponse;
import com.simon.http.model.UserQuery;
import com.simon.system.dao.UserDeptMapper;
import com.simon.system.dao.UserMapper;
import com.simon.system.dao.UserRoleMapper;
import com.simon.system.model.User;
import com.simon.system.model.UserDept;
import com.simon.system.model.UserRole;
import com.simon.system.service.UserService;
import com.simon.token.TokenUtil;
import com.simon.utils.Md5Utils;
import com.simon.utils.Utils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;

/**
 * @ClassName UserServiceImpl
 * @Description 用户服务
 * @Author Jiajie.Mao
 * @Date 2018/6/5 9:38
 * @Version 1.0
 **/
@Service
public class UserServiceImpl implements UserService {

    private static final Logger LOGGER = LoggerFactory.getLogger(UserServiceImpl.class);

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private UserRoleMapper userRoleMapper;

    @Autowired
    private UserDeptMapper userDeptMapper;

    @Autowired
    private TokenUtil tokenUtil;

    /***
     * 增加用户
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public int addUser(User user) {

        try {
            //密码MD5加密
            user.setPassword(Md5Utils.getEncryptedPwd(user.getPassword().trim()));
            user.setCreatetime(new Date());

            return userMapper.insert(user);
        } catch (Exception ex) {
            throw new OperationFailedException(ex.getLocalizedMessage());
        }

    }

    /***
     * 根据用户id获取用户信息
     */
    @Override
    public User getUserById(int id) {
        try {
            User user = userMapper.selectByPrimaryKey(id);
            if (user != null) {
                //获取角色
                user.setRoleId(getRoleId(id));

                //获取部门
                user.setDeptId(getDeptId(id));
            }

            return user;
        } catch (Exception ex) {
            throw new OperationFailedException(ex.getLocalizedMessage());
        }

    }

    /**
     * 查找所有用户信息
     */
    @Override
    public List<User> findAllUser() {
        try {
            List<User> users = userMapper.selectUsers();

            for (User user : users) {
                //获取角色
                user.setRoleId(getRoleId(user.getId()));

                //获取部门
                user.setDeptId(getDeptId(user.getId()));
            }

            return users;
        } catch (Exception ex) {
            throw new OperationFailedException(ex.getLocalizedMessage());
        }
    }

    /***
     * 分页查找用户信息
     */
    @Override
    public List<User> queryUsers(UserQuery userQuery) {
        try {
            PageHelper.startPage(userQuery.getPageNum(), userQuery.getPageSize());
            List<User> users = userMapper.queryUsers(userQuery);

            for (User user : users) {
                //获取角色
                user.setRoleId(getRoleId(user.getId()));

                //获取部门
                user.setDeptId(getDeptId(user.getId()));
            }

            return users;
        } catch (Exception ex) {
            throw new OperationFailedException(ex.getLocalizedMessage());
        }
    }

    @Override
    public PResponse calPage(UserQuery userQuery) {
        try {
            List<User> users = userMapper.queryUsers(userQuery);
            PResponse bPage = new PResponse();
            if (!users.isEmpty()) {
                bPage.setTotalElements(users.size());
                bPage.setTotalPage(Utils.calPages(users.size(), userQuery.getPageSize()));
            } else {
                bPage.setTotalElements(0);
                bPage.setTotalPage(0);
            }

            return bPage;
        } catch (Exception ex) {
            throw new OperationFailedException(ex.getLocalizedMessage());
        }
    }

    /***
     * 删除用户
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public int deleteUser(int id) {
        try {
            User user = getUserById(id);
            tokenUtil.deleteTokenByKey(user.getUsername());
            return userMapper.deleteByPrimaryKey(id);
        } catch (Exception ex) {
            throw new OperationFailedException(ex.getLocalizedMessage());
        }
    }

    /***
     * 修改用户
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public int updateUser(User oldUser, User newUser) {
        try {
            int resUser = 0;
            //修改用户
            oldUser.setUsername(newUser.getUsername());
            oldUser.setBirthday(newUser.getBirthday());
            oldUser.setEmail(newUser.getEmail());
            oldUser.setModifytime(new Date());
            oldUser.setName(newUser.getName());
            oldUser.setPhone(newUser.getPhone());
            oldUser.setSex(newUser.getSex());
            oldUser.setStatus(newUser.getStatus());


            //修改用户的角色
            userRoleMapper.deleteByUserId(oldUser.getId());
            UserRole userRole = null;
            for (String roleId : newUser.getRoleId().split(",")) {
                userRole = new UserRole(oldUser.getId(), new Integer(roleId));
                userRoleMapper.insertSelective(userRole);
            }

            //修改用户的部门
            userDeptMapper.deleteByUserId(oldUser.getId());
            UserDept userDept = null;
            for (String deptId : newUser.getDeptId().split(",")) {
                userDept = new UserDept(oldUser.getId(), new Integer(deptId));
                userDeptMapper.insertSelective(userDept);
            }

            //修改用户
            resUser = userMapper.updateByPrimaryKey(oldUser);

            return resUser;
        } catch (Exception ex) {
            throw new OperationFailedException(ex.getLocalizedMessage());
        }

    }

    /***
     * 根据用户名查找用户
     */
    @Override
    public User findByUsername(String username) {
        try {
            User user = userMapper.findByUsername(username);
            if (user != null){
                //获取角色
                user.setRoleId(getRoleId(user.getId()));

                //获取部门
                user.setDeptId(getDeptId(user.getId()));
            }

            return user;
        } catch (Exception ex) {
            throw new OperationFailedException(ex.getLocalizedMessage());
        }
    }

    /**
     * 修改密码
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public int changePassword(User user) {
        try {
            return userMapper.changePassword(user);
        } catch (Exception ex) {
            throw new OperationFailedException(ex.getLocalizedMessage());
        }
    }

    /**
     * 冻结用户
     */
    @Override
    public int freezeUser(User user) {
        try {
            //1表示冻结用户
            user.setStatus(1);
            user.setModifytime(new Date());
            return userMapper.updateStatus(user);
        } catch (Exception ex) {
            throw new OperationFailedException(ex.getLocalizedMessage());
        }
    }

    /**
     * 取消冻结用户
     */
    @Override
    public int unFreezeUser(User user) {
        try {
            //0表示启用用户
            user.setStatus(0);
            user.setModifytime(new Date());
            return userMapper.updateStatus(user);
        } catch (Exception ex) {
            throw new OperationFailedException(ex.getLocalizedMessage());
        }
    }

    /**
     * 设置用户的角色
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public int setRoles(int id, String roleIds) {
        try {
            //修改用户的角色
            String[] arrRoleIds = roleIds.split(",");
            UserRole userRole = null;
            userRoleMapper.deleteByUserId(id);
            int res = 0;
            for (String roleId : arrRoleIds) {
                userRole = new UserRole(id, new Integer(roleId));
                res = res + userRoleMapper.insertSelective(userRole);
            }

            return res;
        } catch (Exception ex) {
            throw new OperationFailedException(ex.getLocalizedMessage());
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public int setDepts(int id, String deptIds) {
        try {
            //修改用户的部门
            String[] arrDeptIds = deptIds.split(",");
            UserDept userDept;
            userDeptMapper.deleteByUserId(id);
            int res = 0;
            for (String deptId : arrDeptIds) {
                userDept = new UserDept(id, new Integer(deptId));
                res = res + userDeptMapper.insertSelective(userDept);
            }

            return res;
        } catch (Exception ex) {
            throw new OperationFailedException(ex.getLocalizedMessage());
        }
    }

    /**
     * 根据用户id获取角色的id
     */
    @Override
    public String getRoleId(int id) {
        try {
            //获取角色
            List<UserRole> userRoles = userRoleMapper.selectByUserId(id);
            StringBuilder sbRole = new StringBuilder();
            if (!userRoles.isEmpty()) {
                for (UserRole userRole : userRoles) {
                    sbRole.append(userRole.getSysRoleId());
                    sbRole.append(",");
                }
                sbRole.deleteCharAt(sbRole.length() - 1);
            }

            return sbRole.toString();
        } catch (Exception ex) {
            throw new OperationFailedException(ex.getLocalizedMessage());
        }
    }

    /**
     * 根据用户id获取部门id
     */
    @Override
    public String getDeptId(int id) {
        try {
            //获取部门
            List<UserDept> userDepts = userDeptMapper.selectByUserId(id);

            StringBuilder sbDept = new StringBuilder();
            if (!userDepts.isEmpty()) {
                for (UserDept userDept : userDepts) {
                    sbDept.append(userDept.getSysDeptId());
                    sbDept.append(",");
                }
                sbDept.deleteCharAt(sbDept.length() - 1);
            }

            return sbDept.toString();
        } catch (Exception ex) {
            throw new OperationFailedException(ex.getLocalizedMessage());
        }
    }
}
